<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ProjectsController
 *
 * @author Zoila
 */
class ProjectsController extends AppController{
    //put your code here
    public $uses = array('Project','Organization','Upload','Team','ProjectMember','ProjectTeam','Story','Member','User','Role','MemberPoint','RolePrivilege','Privilege','Retrospective');
   // var $helpers = array('Calendar.Calendar');
    //AUTORIZACION
    public function isAuthorized($user) {
         if (in_array($this->action, array('view'))) {
            return true;
        }
        if(!$this->Session->check('Organization')){
            $this->refreshSession($this->request->params['pass'][0]);
//            $this->Session->setFlash('Elija una organización');
//            $this->redirect(array('controller'=>'organizations','action'=>'index'));
//            return false;
        }

        if (in_array($this->action, array('planning','reunion','retrospective','add','members','editRole','repository','role','addRole', 'backlog','view', 'backlogGrid', 'backlogCard','pokerPlanning','pokerPlanningView'))) {
            
            return true;
        }

        // The owner of a post can edit and delete it
        if (in_array($this->action, array('edit', 'delete'))) {
            $proyectId = $this->request->params['pass'][0];
            if ($this->Project->isOwnedBy($proyectId, $user['id'])) {
                return true;
            }
        }
        
        return parent::isAuthorized($user);
    }
    public function findPermisos($id,$per=null){
        $rol=$this->ProjectMember->findByProjectIdAndUserId($id,$this->Auth->user('id'));
        //$this->set('rol',$rol);
        if (is_null($per)){
            $pri=$this->RolePrivilege->findAllByRoleIdAndProjectId($rol['Role']['id'],$id);
            $this->set('permisos',$pri);
        }
        else{
            $pri=$this->RolePrivilege->findByRoleIdAndProjectIdAndPrivilegeI($rol['Role']['id'],$id,$per);
            if(!is_null($pri)){                
                $this->set('permiso',$pri['RolePrivilege']['state']);
            }
            else
                $this->set('permiso',false);
        }
//        var_dump($pri);
        return $pri;
        
    }
    public function reunion($id){
        $this->refreshSession($id);
        $this->findPermisos($id,3);//Editar Historias=3
        $this->set('idProject',$id); //ZP: se usa en el enlace de navs
        $this->Project->id = $id;
        $pro=$this->Project->read();
        $this->set('project',$pro );
        
    }
    public function planning($id,$ac=0,$sprint=null){
        $this->backlog($id,$sprint);
        $this->set('accordion',$ac);
    }
    public function retrospective($id,$sprint=0){
        $this->refreshSession($id);
        $this->findPermisos($id,3);//Editar Historias=3
        $this->set('idProject',$id); //ZP: se usa en el enlace de navs
        $this->Project->id = $id;
        $pro=$this->Project->read();
        $this->set('project',$pro );
        $retros= $this->Retrospective->findAllByProjectIdAndSprint($id,$sprint);
        $this->set('retros',$retros);
    }
    public function pokerPlanning($id = null,$sprint=null) {
        $this->set('idProject',$id); //ZP: se usa en el enlace de navs
        $this->Project->id = $id;
        $pro=$this->Project->read();
        if ($this->Auth->user()!=NULL && ($this->validate($pro)))
            $this->set('project',$pro );
        
        if ($sprint!=null){
            $this->Story->unbindModel(
                    array('belongsTo' => array('Project'))
            );
            $stories=$this->Story->findAllByProjectIdAndSprint($id,$sprint);
            $this->set('stories',$stories);
            $this->set('SprintStories',true);
        }
        else{
            $this->Story->unbindModel(
                    array('belongsTo' => array('Project'))
            );
            $stories=$this->Story->findAllByProjectId($id);
            $this->set('stories',$stories);
        }
        $p_member=$this->ProjectMember->findAllByProjectId($id);
        $members=array();
        foreach($p_member as $m){
            array_push($members,$m['User']);
        }
        $this->set('members',$members );
        
    }
     public function pokerPlanningView($id = null,$sprint=null) {
        $this->set('idProject',$id); //ZP: se usa en el enlace de navs
        $this->Project->id = $id;
        $pro=$this->Project->read();
        if ($this->Auth->user()!=NULL && ($this->validate($pro)))
            $this->set('project',$pro );
        
        if ($sprint!=null){
            $this->Story->unbindModel(
                    array('belongsTo' => array('Project'))
            );
            $stories=$this->Story->findAllByProjectIdAndSprint($id,$sprint);
            for($i=0;$i<count($stories);$i++){
                $stories[$i]['MemberPoint']=$this->MemberPoint->findAllByStoryId($stories[$i]['Story']['id']);
            }
            
            $this->set('stories',$stories);
            $this->set('SprintStories',true);
        }
        else{
            $this->Story->unbindModel(
                    array('belongsTo' => array('Project'))
            );
            $stories=$this->Story->findAllByProjectId($id);
            for($i=0;$i<count($stories);$i++){
                $stories[$i]['MemberPoint']=$this->MemberPoint->findAllByStoryId($stories[$i]['Story']['id']);
            }
            
            $this->set('stories',$stories);
        }
        $p_member=$this->ProjectMember->findAllByProjectId($id);
        $members=array();
        foreach($p_member as $m){
            array_push($members,$m['User']);
        }
        $this->set('members',$members );
        
    }
    
    public function editRole($projectId=null,$memberId=null) {
        if ($this->request->is('get')) {
                $this->request->data = $this->ProjectMember->findByProjectIdAndUserId($projectId ,$memberId);
            } else {
                $this->ProjectMember->updateAll(
                    array('ProjectMember.role_id'=>($this->request->data['ProjectMember']['role_id'])),
                    array('ProjectMember.user_id'=>($this->request->data['ProjectMember']['user_id']),'ProjectMember.project_id'=>($this->request->data['ProjectMember']['project_id']))
                    );
                $this->redirect(array('action'=>'members',$this->request->data['ProjectMember']['project_id']));
            }

    }
    public function role($projectId=null) {
        
        $this->refreshSession($projectId);
        $this->set('roles',$this->Role->findAllByProjectId($projectId));
        $this->Project->unbindModel(
                    array('hasAndBelongsToMany' => array('Team'),'hasMany' => array ('Story'))
                );
        $this->set('project',$this->Project->findById($projectId));
        if ($this->request->is('post')){
            for ($i=0;$i<(count ($this->request->data['RolePrivilege'])); $i++){
                for ($j=0;$j<(count ($this->request->data['RolePrivilege'][$i])); $j++){
                    $cambios=true;                    
                    if(!is_null($this->request->data['RolePrivilege'][$i][$j]['state'])){
                        
                        $bool = (($this->request->data['RolePrivilege'][$i][$j]['state'])==1);
                        $cambios &= $this->RolePrivilege->updateAll(
                            array('RolePrivilege.state'=>$bool),
                            array('RolePrivilege.role_id'=>($this->request->data['RolePrivilege'][$i][$j]['role_id']),'RolePrivilege.privilege_i'=>($this->request->data['RolePrivilege'][$i][$j]['privilege_i']))
                        );
                    }
                }
            }
            if ($cambios){
                $this->Session->setFlash(_t('cambiosTrue'));
                $this->redirect(array('action'=>'members',$projectId));
            }
            if ($cambios){
                 $this->Session->setFlash(_t('cambiosFalse'));
            }
            
        }    

    }
    

    public function members($id ,$s =null) {
        
        $this->findPermisos($id,1);//AgregarUser=1
        
        $this->ProjectMember->unbindModel(
                    array('belongsTo' => array('Project'))
                );

        $projectMembers=$this->ProjectMember->findAllByProjectId($id);
        $roles=$this->Role->findAllByProjectId($id);
        

        $projectTeams=$this->ProjectTeam->findByProjectIdAndIsDefault($id,1);
    
        $this->set('defaultTeam',$projectTeams);


//            $this->Team->id = $id;
//            $team=$this->Team->read();
            if ($this->Auth->user()!=NULL ) {
                $this->set('members',$projectMembers);
                $this->set('roles',$roles);
                $this->set('defaultTeam',$projectTeams);
            }
//                $this->set('team',$team );

        if (($s != null) && ($s==='find')) {
            if ($this->request->is('post')){
                $arr=array();
                for($i=0;$i<count($projectMembers);$i++){
                    $arr[]=$projectMembers[$i]['ProjectMember']['user_id'];
                }

                $this->User->unbindModel(
                    array('hasMany' => array('Organization'))
                );

                $users=$this->User->find('all', array('conditions' => array('NOT' => array('User.id' => $arr),'User.username LIKE'=>'%'.$this->request->data['Team']['buscar'].'%'),'order' => 'User.username'));
                $this->set('users',$users);

            }
        }

    }
    
    public function addRole(){
     
        if ($this->request->is('post')){
            if (strcmp($this->request->data['Role']['description'],"")==0){
                $this->Session->setFlash(_t('cambiosFalse'));
                $this->redirect(array('action'=>'role',$this->request->data['Role']['project_id']));
                return;
            }
                    
            if($this->Role->save($this->request->data)){
                
                    $this->refreshSession( $this->request->data['Role']['project_id']);
                    //CREO UN EQUIPO
                    $roleId = $this->Role->id;
                    $priv= $this->Privilege->find('all');
                    foreach($priv as $p){
                        $role_priv= array('privilege_i'=> $p['Privilege']['id'],
                         'role_id'=> $roleId,
                         'project_id' => $this->request->data['Role']['project_id'],
                         'state' => false);
                        $this->RolePrivilege->save($role_priv);
                    }
                $this->Session->setFlash(_t('cambiosTrue'));
                $this->redirect(array('action'=>'role',$this->request->data['Role']['project_id']));
                    
            }
        }
            
            
    }
    
    public function add( $idOrg = null){
        if ($idOrg!=null){
            if ($this->request->is('post')){  
                $this->request->data['Project']['creator_id'] = $this->Auth->user('id');
                $this->request->data['Project']['organization_id'] = $idOrg;
                $this->request->data['Project']['sprints']=1;//ZP: Por defecto se crea un Sprint
                if($this->Project->save($this->request->data)){
                    //CREO UN EQUIPO
                    $idPro = $this->Project->id;
                    $team= array(//'team_id'=> $this->Team->id,
                         'organization_id'=> $idOrg,
                         'creator_id'=> $this->Auth->user('id'),
                         'name' => $this->request->data['Project']['name']);
                    
                    if($this->Team->save($team)){
                    
                        //ZP: Guardar en la clase asociativa
                        $project_team = array('team_id'=> $this->Team->id,
                            'project_id'=> $idPro,
                            'creator_id'=> $this->Auth->user('id'),
                            'name' => $this->request->data['Project']['name'] ,
                            'is_default' => 1);
                        
                        $member = array('user_id'=> $this->Auth->user('id'),
                            'team_id'=>$this->Team->id,
                            'name' => $this->Auth->user('username'),
                            'state'=>1,'sent_by'=>$this->Auth->user('id'));
                        $projectMember=array(
                            'user_id'=> $this->Auth->user('id'),
                            'team_id'=>$this->Team->id,
                            'project_id'=>$idPro
                            );
                        if ($this->ProjectTeam->save($project_team)){
                            $this->Member->save($member);
                            $this->ProjectMember->save($projectMember);
                            
                        }else{
                            $this->Session-> setFlash('Unable to add your projectTeam');
                            $this->redirect(array('controller'=>'organizations','action'=>'view',$idOrg));
                        }
                        
                        //CREO LOS ROLES POR DEFECTO
                        //MASTER
                        $priv= $this->Privilege->find('all');
                        $rolMaster=array(
                            'description'=> 'ScrumMaster',
                            'project_id'=>$idPro
                            );
                        
                        if($this->Role->save($rolMaster)){
                            
                            $roleId = $this->Role->id;
                            foreach($priv as $p){
                                    $role_priv= array('privilege_i'=> $p['Privilege']['id'],
                                    'role_id'=> $roleId,
                                    'project_id' => $idPro,
                                    'state' => true);
                                    $this->RolePrivilege->save($role_priv);
                            }
                            unset($this->Role->id);
                        }
                        else{
                            $this->Session-> setFlash('Error al crear los role: '.$roleId.' del Projecto: '. $idPro );
                            $this->redirect(array('controller'=>'organizations','action'=>'view',$idOrg));
                        }


                         //EQUIPO
                        $rolTeam=array(
                            'description'=> 'Equipo',
                            'project_id'=>$idPro
                            );
                        
                        if($this->Role->save($rolTeam)){
                            $roleId = $this->Role->id;
                            foreach($priv as $p){
                                    $role_priv= array('privilege_i'=> $p['Privilege']['id'],
                                    'role_id'=> $roleId,
                                    'project_id' => $idPro,
                                    'state' => false);
                                    $this->RolePrivilege->save($role_priv);
                            }

                            unset($this->Role->id);
                        }
                         else{
                            $this->Session-> setFlash('Error al crear los rol: '.$roleId.' del Projecto: '. $idPro );
                            $this->redirect(array('controller'=>'organizations','action'=>'view',$idOrg));
                        }
                        //Owner
                        $rolOwner=array(
                            'description'=> 'Propietario',
                            'project_id'=>$idPro
                            );
                        
                        if($this->Role->save($rolOwner)){
                            $roleId = $this->Role->id;
                            foreach($priv as $p){
                                    $role_priv= array('privilege_i'=> $p['Privilege']['id'],
                                    'role_id'=> $roleId,
                                    'project_id' => $idPro,
                                    'state' => true);
                                    $this->RolePrivilege->save($role_priv);
                            }
                            unset($this->Role->id);
                        }
                        else{
                            $this->Session-> setFlash('Error al crear los rol: '.$roleId.'del Projecto: '. $idPro );
                            $this->redirect(array('controller'=>'organizations','action'=>'view',$idOrg));
                        }

                        $this->Session->setFlash('Your project has been saved.');
                        $this->redirect(array('controller'=>'projects','action'=>'view',$idPro));



                        
                    }else{
                        $this->Session-> setFlash('Unable to add your Team');
                        $this->redirect(array('controller'=>'organizations','action'=>'view',$idOrg));
                    }
                }
                
                else{
                    $this->Session-> setFlash('Unable to add your project');
                    $this->redirect(array('controller'=>'organizations','action'=>'view',$idOrg));
                }
            }
        }
        else {
            $this->set('error',true);
        }
        
        
    }
    
    public function delete($id) {
        $project=$this->Project->findById($id);
        $idOrg=$org['Project']['organization_id'];
        $project['Project']['active']=false;
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }
        if ($this->Project->save($project)) {
            $this->Session->setFlash('The Project with id: ' . $id . ' has been deleted.');
            $this->redirect(array('controller'=>'organizations','action'=>'view',$idOrg));
        }
        

    }
    
    public function edit($id = null) {
        $this->refreshSession($id);
        $pro=$this->Project->findById($id);
        $idOrg=$pro['Project']['organization_id'];
        $sprints=$pro['Project']['sprints'];
       // var_dump($this->request->data['Project']);
        $this->Project->id = $id;
        if ($this->request->is('get')) {
            $this->request->data = $this->Project->read();            
        } else {
            if($this->getDuration( $this->request->data)<0){
                $this->Session->setFlash('Rango de fechas incorrecto');
                return;
            }
            $this->request->data['Project']['begin']=explode('-',$this->request->data['Project']['begin']);
            $this->request->data['Project']['end']=explode('-',$this->request->data['Project']['end']);
            $keys = array('day', 'month', 'year') ;
            $this->request->data['Project']['begin'] = array_combine($keys, array_values($this->request->data['Project']['begin']));
            $this->request->data['Project']['end'] = array_combine($keys, array_values($this->request->data['Project']['end']));

            if ($sprints > $this->request->data['Project']['sprints']){
                $this->Session->setFlash('No puede disminuir la cantidad de Sprints');

            }
            else {
                    if ($this->Project->save($this->request->data)) {
                        $this->Session->setFlash('Your project has been updated.');
                        $this->redirect(array('action' => 'view',$id));
                    } else {
                        $this->Session->setFlash('Unable to update your project.');
                    }
                    
            }
        }
        
    }
    
    public function index($idOrg=null){ // ZP: solo puedo ver mis organizaciones , PROYECTOS EN LA ORGANIZACION
        if (($this->Auth->user()!=NULL) && ($idOrg!=NULL)){
            $this->set('projects',  $this->Project->find('all',array('conditions' => array('Project.organization_id =' => $idOrg))));
            $this->set('org',$this->Organization->findById($idOrg));
        }
        
    }
    
    public function backlogGrid($id = null,$sprint=null) {
        $this->backlog($id,$sprint);
//        $this->findPermisos($id,3);//Editar Historias=3
//        $this->refreshSession($id);
//       $this->set('idProject',$id); //ZP: se usa en el enlace de navs
//        $this->Project->id = $id;
//        $pro=$this->Project->read();
//        
//        if ($this->Auth->user()!=NULL && ($this->validate($pro)))
//            $this->set('project',$pro );
//        if ($sprint!=null){
//            $this->Story->unbindModel(
//                    array('belongsTo' => array('Project'))
//            );
//            $stories=$this->Story->findAllByProjectIdAndSprint($id,$sprint);
//            $this->set('stories',$stories);
//            $this->set('SprintStories',true);
//        }
//        else{
//            $this->Story->unbindModel(
//                    array('belongsTo' => array('Project'))
//            );
//            $stories=$this->Story->findAllByProjectId($id);
//            $this->set('stories',$stories);
//        }
//        $p_member=$this->ProjectMember->findAllByProjectId($id);
//        $members=array();
//        foreach($p_member as $m){
//            array_push($members,$m['User']);
//        }
//        $this->set('members',$members );
    }
    
    public function backlogCard($id = null,$sprint=null) {
        $this->backlog($id,$sprint);
//        $this->findPermisos($id,3);//Editar Historias=3
//        $this->refreshSession($id);
//        $this->set('idProject',$id); //ZP: se usa en el enlace de navs
//        $this->Project->id = $id;
//        $pro=$this->Project->read();
//        
//        if ($this->Auth->user()!=NULL && ($this->validate($pro)))
//            $this->set('project',$pro );
//        if ($sprint!=null){
//            $this->Story->unbindModel(
//                    array('belongsTo' => array('Project'))
//            );
//            $stories=$this->Story->findAllByProjectIdAndSprint($id,$sprint);
//            $this->set('stories',$stories);
//            $this->set('SprintStories',true);
//        }
//        else{
//            $this->Story->unbindModel(
//                    array('belongsTo' => array('Project'))
//            );
//            $stories=$this->Story->findAllByProjectId($id);
//            $this->set('stories',$stories);
//        }
//        $p_member=$this->ProjectMember->findAllByProjectId($id);
//        $members=array();
//        foreach($p_member as $m){
//            array_push($members,$m['User']);
//        }
//        $this->set('members',$members );
        
    }
    
    
     public function view($id = null) {
        $this->set('idProject',$id); //ZP: se usa en el enlace de navs
        $this->Project->id = $id;
        $pro=$this->Project->read();
        $this->refreshSession($id);
        
        
        $arr=array();
        for($i=0;$i<count($pro['Team']);$i++){
            $arr[]=$pro['Team'][$i]['id'];
        }

        $teams=$this->Team->find('all', array('conditions' => array('Team.organization_id' => $pro['Project']['organization_id'],'NOT' => array('Team.id' => $arr)),'order' => 'Team.id'));
        $this->set('teamsOrg',$teams);
        
        
        if ($this->Auth->user()!=NULL && ($this->validate($pro))){
            
            $pro['Project']['duration']=$this->getDuration($pro);;
            
             $this->Story->unbindModel(
                    array('belongsTo' => array('Project'),'hasMany'=>array('MemberPoint'))
            );
            $pro['Stories']=$stories=$this->Story->findAllByProjectId($id);
            $j=0;$state1=0;$state3=0;
            for($i=0;$i<count($pro['Stories']);$i++){
                
                $k=$pro['Stories'][$i]['Story']['points'];
                if($k>0&&$k<6){
                    $j+=$k;
                }
                switch($pro['Stories'][$i]['Story']['state']){
                    case 1: $state1++;break;
                    case 2: $state1++;break;
                    case 3: $state3++;break;
                }
                $pro['Stories'][$i]['Story']['duration']=$this->getDurationGenerico($pro['Stories'][$i]['Story']['begin'],$pro['Stories'][$i]['Story']['end']);
            }
            $pro['Project']['points']=$j;
            $pro['Project']['enProgreso']=$state1;
            $pro['Project']['terminadas']=$state3;
            $this->set('project',$pro );
            
            //$this->set('duration',$this->Project->getVirtualField('duration'));
        }
        

    }
    public function getDuration($project){
        $year=(strftime("%Y",strtotime($project['Project']['end']))-strftime("%Y",strtotime($project['Project']['begin'])));
        //$month=(strftime("%m",strtotime($project['Project']['end']))-strftime("%m",strtotime($project['Project']['begin'])));
        $days=(strftime("%j",strtotime($project['Project']['end']))-strftime("%j",strtotime($project['Project']['begin'])));
        return $year*365+$days;
    }
    public function getDurationGenerico($ini,$fin){
         $year=(strftime("%Y",strtotime($fin))-strftime("%Y",strtotime($ini)));
        //$month=(strftime("%m",strtotime($project['Project']['end']))-strftime("%m",strtotime($project['Project']['begin'])));
        $days=(strftime("%j",strtotime($fin))-strftime("%j",strtotime($ini)));
        return $year*365+$days;
    }
    public function validate($pro){

        $users=$this->ProjectMember->findByProjectIdAndUserId($pro['Project']['id'], $this->Auth->user('id'));
        return $users!=null;
    }
    public function repository($id,$folder=0){
        $this->refreshSession($id);
        $this->Project->id = $id;
        $pro=$this->Project->read();
        $this->set('project',$pro );
        $uploads=$this->Upload->find('all', array(
		'conditions' => array(
			'Upload.project_id' => $id,
                        'Upload.folder_id' => $folder
		)
	));
        if($folder!=0){
            $folderComp=$this->Upload->find('first', array(
		'conditions' => array(
			'Upload.id' => $folder
		)
           ));
            
            if($folderComp['Upload']['folder_id']!=0){
                $folderComp['Parent']= $this->Upload->find('first', array(
                        'conditions' => array(
                                'Upload.id' => $folderComp['Upload']['folder_id']
                        )
                ));
            }
           
            $this->set('folderComplete',$folderComp);
        }
        $this->set('uploads',$uploads);
        $this->set('folderAct',$folder);
    }
    public function backlog($id = null,$sprint=null) {
        
        $this->refreshSession($id);
        $this->findPermisos($id,3);//Editar Historias=3
        $this->set('idProject',$id); //ZP: se usa en el enlace de navs
        $this->Project->id = $id;
        $pro=$this->Project->read();
        $stories=array();
        
        if ($this->Auth->user()!=NULL && ($this->validate($pro))){
            
            if ($sprint!=null){
                $this->Story->unbindModel(
                        array('belongsTo' => array('Project'))
                );
                $stories=$this->Story->findAllByProjectIdAndSprint($id,$sprint);
                //$this->set('stories',$stories);
                $this->set('SprintStories',true);
            }
            else{
                $this->Story->unbindModel(
                        array('belongsTo' => array('Project'))
                );
                $stories=$this->Story->findAllByProjectId($id);
                
            }

            $j=0;$state1=0;$state3=0;
            for($i=0;$i<count($stories);$i++){

                $k=$stories[$i]['Story']['points'];
                if($k>0&&$k<100){
                    $j+=$k;
                }
                switch($stories[$i]['Story']['state']){
                    case 1: $state1++;break;
                    case 2: $state1++;break;
                    case 3: $state3++;break;
                }
                $stories[$i]['Story']['duration']=$this->getDurationGenerico($stories[$i]['Story']['begin'],$stories[$i]['Story']['end']);
            }
            $pro['Project']['points']=$j;
            $pro['Project']['enProgreso']=$state1;
            $pro['Project']['terminadas']=$state3;


            $this->set('stories',$stories);
            $p_member=$this->ProjectMember->findAllByProjectId($id);
            $members=array();
            foreach($p_member as $m){
                array_push($members,$m['User']);
            }
            $this->set('members',$members );
            $this->set('project',$pro );
        }
    }
    
}

?>
